package com.lft.examsys.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lft.examsys.entity.Paper;
import com.lft.examsys.entity.Role;
import com.lft.examsys.entity.User;
import com.lft.examsys.model.IModel;
import com.lft.examsys.service.PermissionService;
import com.lft.examsys.service.RoleService;
import com.lft.examsys.service.UserService;
import com.lft.examsys.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private PasswordEncoder encoder;

    @GetMapping("/personal/{id}")
    @PreAuthorize("hasAnyAuthority('user.personal')")
    public ModelAndView personal(IModel model, @PathVariable Integer id) {
        return model.validation("/user/personal", () -> {
//            List<Paper> paperList = userService.getRecentPapers(id);
//            model.add("papers", paperList);
        }, model::err);
    }


    @PostMapping("/update")
    @PreAuthorize("hasAnyAuthority('user.update')")
    public ModelAndView update(IModel model, MultipartFile userIcon, String prePwd, String newPwd, HttpServletRequest request) throws IOException {
        User origin = model.user();

        return model.validation("/user/personal", () -> {
            List<Paper> paperList = userService.getRecentPapers(origin.getId());
            model.add("papers", paperList);
            User user = new User();
            if (!(prePwd.equals("") && newPwd.equals("")) && !encoder.matches(prePwd, origin.getPassword())) {
                model.failure("原密码错误！！！");
            }
            user.setId(origin.getId());
            if (!StringUtils.isEmpty(userIcon.getOriginalFilename()))
                user.setIcon(FileUtil.uploadFile(userIcon, request, "/img/"));
            if (!StringUtils.isEmpty(newPwd))
                user.setPassword(encoder.encode(newPwd));
            if (!userService.update(user))
                model.failure("用户更新失败");


            user = userService.findByName(origin.getUsername());
            model.user(user);
            model.info("更新成功！");
            List<String> permissions = user.getUsername().equalsIgnoreCase("root") ?
                    permissionService.getAllPermissionName() :
                    permissionService.getActivePermissionIdByRoleId(user.getRoleId());
            user.fillAuthorize(permissions);
        }, model::err);
    }

    @GetMapping("/manage")
    @PreAuthorize("hasAnyAuthority('user.manage')")
    public ModelAndView manage(IModel model, Integer page, Integer size) {
        return model.validation("admin/authorize/UserManagement", () -> {
            List<Role> allRole = roleService.getAllRole();
            Page<User> res = userService.getAllByPage(page, size);
            model.add("users", res.getRecords());
            model.add("page", res.getCurrent());
            model.add("size", res.getSize());
            model.add("total", res.getPages());
            model.add("count", res.getTotal());
            model.add("roles", allRole);
        }, model::err);
    }




    @GetMapping("/role/{id}")
    @PreAuthorize("hasAnyAuthority('user.role')")
    public ModelAndView roleSetPage(IModel model, @PathVariable Integer id, Integer page, Integer size) {
        return model.validation("admin/RoleSet", () -> {
            User user = userService.findById(id);
            List<Role> roles = roleService.getAllRole();
            model.add("roles", roles);
            model.add("u", user);
            model.add("page", page);
            model.add("size", size);
        }, model::err);
    }

    @PostMapping("/role/{id}")
    @PreAuthorize("hasAnyAuthority('user.role')")
    public ModelAndView role(IModel model, @PathVariable Integer id, String role, String page, String size) {
        return model.validation("redirect:/user/manage?page=" + page + "&size=" + size, () -> {
            userService.SetRole(id, role);
        }, model::err);
    }

    @PostMapping("/ban/{id}")
    @PreAuthorize("hasAnyAuthority('user.ban')")
    public ModelAndView ban(IModel model, @PathVariable Integer id, Boolean banned, Integer page, Integer size) {
        return model.validation("redirect:/user/manage?page=" + page + "&size=" + size, () -> {
            if (userService.findById(id).getUsername().equalsIgnoreCase("root"))
                model.failure("不能封禁超级用户");

            userService.ban(id, banned);
        }, model::err);
    }


}
